package com.cooler.floatview;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;

public class MainActivity extends Activity
{
	private static final String TAG = "Vtag";//MainActivity.class.getSimpleName();
	private static final int SWITCH_CAMERA = 1;
	
	private Messenger mService;
	private ServiceConnection mConnection = new ServiceConnection() {	
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
		}
	};
	
	private static Messenger mMessenger = new Messenger(new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 2) {
				Log.d(TAG, "message from service, current camera: " + msg.arg1);
			} else {
				super.handleMessage(msg);
			}
		}
	});
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		setupViews();
	}

	private void setupViews() {
		Button buttonStart = (Button) findViewById(R.id.button_start);
		Button buttonStop  = (Button) findViewById(R.id.button_stop);
		Button buttonSwitch = (Button) findViewById(R.id.button_switch);
		
		buttonStart.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				bindService(new Intent(MainActivity.this, FloatService.class), 
						mConnection, BIND_AUTO_CREATE);
				Log.d(TAG, "start service to add the float window");
			}
		});
		
		buttonStop.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
				unbindService(mConnection);
				Log.d(TAG, "stop the service to remove the float window");
			}
		});
		
		buttonSwitch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Message message = Message.obtain(null, SWITCH_CAMERA, 2, 1);
				message.replyTo = mMessenger;
				try {
					mService.send(message);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}
